import { PlusOutlined } from '@ant-design/icons';
import { Input, InputRef, Space, Tag, theme, Tooltip } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

interface TagGroupProps {
  style?: React.CSSProperties;
  value?: string[];
  onChange?: (value: string[]) => void;
}

const TagGroup: React.FC<TagGroupProps> = ({ style, value, onChange }) => {
  const { token } = theme.useToken();

  const [tags, setTags] = useState(value || []);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [editInputIndex, setEditInputIndex] = useState(-1);
  const [editInputValue, setEditInputValue] = useState('');
  const inputRef = useRef<InputRef>(null);
  const editInputRef = useRef<InputRef>(null);

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  useEffect(() => {
    console.log('===11111===', value);

    if (value !== undefined) {
      setTags(value);
    }
  }, [value]);

  useEffect(() => {
    editInputRef.current?.focus();
  }, [editInputValue]);

  const handleClose = (removedTag: string) => {
    const newTags = tags.filter((tag) => tag !== removedTag);
    console.log();
    setTags(newTags);
    if (onChange) {
      onChange(newTags);
    }
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // let reg = new RegExp('^[\u4E00-\u9FA5A-Za-z0-9]+$');

    // if (e.target.value.trim().length > 0 && reg.test(e.target.value.trim())) {
    //   setInputValue(e.target.value.trim());
    // } else {
    //   setInputValue('');
    // }

    setInputValue(e.target.value.trim());
  };

  const handleInputConfirm = () => {
    let reg = new RegExp('^[\u4E00-\u9FA5A-Za-z0-9]+$');

    if (inputValue && !tags.includes(inputValue) && reg.test(inputValue)) {
      setTags([...tags, inputValue]);
      if (onChange) {
        onChange([...tags, inputValue]);
      }
    }
    setInputVisible(false);
    setInputValue('');
  };

  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditInputValue(e.target.value);
  };

  const handleEditInputConfirm = () => {
    const newTags = [...tags];
    newTags[editInputIndex] = editInputValue;
    setTags(newTags);
    if (onChange) {
      onChange(newTags);
    }
    setEditInputIndex(-1);
    setEditInputValue('');
  };

  const tagInputStyle: React.CSSProperties = {
    width: 100,
    height: 22,
    marginInlineEnd: 8,
    verticalAlign: 'top',
  };

  const tagPlusStyle: React.CSSProperties = {
    width: 100,
    height: 22,
    background: token.colorBgContainer,
    borderStyle: 'dashed',
    textAlign: 'center',
  };

  return (
    <Space style={style} size={[0, 8]} wrap>
      {tags.map((tag, index) => {
        if (editInputIndex === index) {
          return (
            <Input
              ref={editInputRef}
              key={tag}
              size="small"
              style={tagInputStyle}
              value={editInputValue}
              onChange={handleEditInputChange}
              onBlur={handleEditInputConfirm}
              onPressEnter={handleEditInputConfirm}
            />
          );
        }
        const isLongTag = tag.length > 20;
        const tagElem = (
          <Tag
            key={tag}
            closable={true}
            style={{ userSelect: 'none' }}
            onClose={() => handleClose(tag)}
          >
            <span
              onDoubleClick={(e) => {
                setEditInputIndex(index);
                setEditInputValue(tag);
                e.preventDefault();
              }}
            >
              {isLongTag ? `${tag.slice(0, 20)}...` : tag}
            </span>
          </Tag>
        );
        return isLongTag ? (
          <Tooltip title={tag} key={tag}>
            {tagElem}
          </Tooltip>
        ) : (
          tagElem
        );
      })}
      {inputVisible ? (
        <Input
          ref={inputRef}
          type="text"
          size="small"
          style={tagInputStyle}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      ) : (
        <Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
          新增标签
        </Tag>
      )}
    </Space>
  );
};
export default TagGroup;
